#include "Socket.hpp"
#include "Protocol.hpp"

void Usage(const char *process)
{
    std::cout << "usage: \n\t";
    std::cout << process << " server_ip server_port" << std::endl;
}

// ./clientcal ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    Socket sk;
    sk.CreateSock();
    int cnt = 0;
    srand(time(nullptr) ^ getpid());

    std::string opers = "+-*/%^#@!>?+-";
    char result[1024];
    bool b = sk.Connect(server_ip, server_port);
    if (!b)
    {
        std::cerr << "connect error" << std::endl;
        return 1;
    }
    while (cnt++ < 10)
    {
        int data1 = rand() % 100 + 1;
        usleep(4321);
        int data2 = rand() % 100;
        char oper = opers[rand() % opers.size()];
        Request req(data1, data2, oper);
        std::string content;
        req.Serialize(&content);
        content = Encapsulation(content);
        std::cout << "create task success:\n"
                  << content << std::endl;
        ssize_t n = write(sk.GetSockFd(), content.c_str(), content.size());
        if (n <= 0)
            std::cerr << "client, write error" << std::endl;
        sleep(1);
        n = read(sk.GetSockFd(), result, sizeof(result));
        if (n > 0)
        {
            result[n] = 0;
            std::cout << "calculate success, result:\n"
                      << result << std::endl;
        }
        sleep(1);
    }
    sk.Close();
    return 0;
}